// pages/calculator/calculator.js
const app = getApp();
const MortgageCalculator = require('../../utils/mortgageCalculator.js');

Page({
  data: {
    loanAmount: '',
    loanTerm: 30,
    interestRate: 4.9,
    paymentMethod: 'equal_payment',
    result: null,
    showResult: false,
    loading: false
  },

  onLoad(options) {
    if (options.type === 'early') {
      this.setData({ activeTab: 'early_repayment' });
    }
  },

  onLoanAmountInput(e) {
    this.setData({ loanAmount: e.detail.value });
  },

  onLoanTermInput(e) {
    this.setData({ loanTerm: parseInt(e.detail.value) });
  },

  onInterestRateInput(e) {
    this.setData({ interestRate: parseFloat(e.detail.value) });
  },

  onPaymentMethodChange(e) {
    this.setData({ paymentMethod: e.detail.value });
  },

  calculate() {
    const { loanAmount, loanTerm, interestRate, paymentMethod } = this.data;
    
    if (!loanAmount || loanAmount <= 0) {
      app.showError('请输入有效的贷款金额');
      return;
    }
    
    this.setData({ loading: true });
    
    try {
      let result;
      const monthlyRate = interestRate / 100 / 12;
      
      if (paymentMethod === 'equal_payment') {
        result = MortgageCalculator.equalPayment(loanAmount, loanTerm, monthlyRate);
      } else {
        result = MortgageCalculator.equalPrincipal(loanAmount, loanTerm, monthlyRate);
      }
      
      this.saveCalculation({ loanAmount, loanTerm, interestRate, paymentMethod, result });
      
      this.setData({
        result,
        showResult: true,
        loading: false
      });
      
      app.showSuccess('计算完成');
      
    } catch (error) {
      console.error('计算错误:', error);
      app.showError('计算失败，请检查输入参数');
      this.setData({ loading: false });
    }
  },

  saveCalculation(calculation) {
    const userInfo = app.globalData.userInfo;
    if (userInfo) {
      userInfo.statistics.totalCalculations += 1;
      
      let history = wx.getStorageSync('calculationHistory') || [];
      history.unshift({
        id: `calc_${Date.now()}`,
        ...calculation,
        createdAt: new Date().toISOString()
      });
      
      if (history.length > 50) {
        history = history.slice(0, 50);
      }
      
      wx.setStorageSync('calculationHistory', history);
      wx.setStorageSync('userInfo', userInfo);
      app.globalData.userInfo = userInfo;
    }
  },

  resetForm() {
    this.setData({
      loanAmount: '',
      loanTerm: 30,
      interestRate: 4.9,
      paymentMethod: 'equal_payment',
      result: null,
      showResult: false
    });
  },

  shareResult() {
    if (!this.data.result) {
      app.showError('没有可分享的计算结果');
      return;
    }
    
    const result = this.data.result;
    const shareText = `房贷计算结果：
贷款金额：${this.data.loanAmount}万元
月供：${result.monthlyPayment.toFixed(2)}元
总利息：${result.totalInterest.toFixed(2)}元
总还款：${result.totalPayment.toFixed(2)}元`;
    
    wx.setClipboardData({
      data: shareText,
      success: () => {
        app.showSuccess('结果已复制到剪贴板');
      }
    });
  },

  onShareAppMessage() {
    return {
      title: '房贷计算器 - 精准计算房贷',
      path: '/pages/calculator/calculator'
    };
  }
}); 